﻿using System;
using System.Runtime.Serialization;

using Matchingo.Common.Types.Interfaces;

namespace Matchingo.Common.Types.Types
{
    /// <summary>
    /// Represents a command as used in the Command Pattern typically used for redo/undo - in this case used for replays
    /// </summary>
    [DataContract]
    public class CardFlipCommand
    {
        // stored in command
        [DataMember]
        public Guid UniqueCardID { get; set; }

        [DataMember]
        public TimeSpan TimeOffset { get; set; }

        public CardFlipCommand() { }

        public CardFlipCommand(Guid uniqueCardID)
        {
            UniqueCardID = uniqueCardID;
        }

		/// <summary>
		/// Executes this command
		/// </summary>
		/// <param name="gameLogic">The game logic against which to execute</param>
		/// <returns>whether or not the card actually flipped</returns>
        public bool Execute(IMemoryGameLogic gameLogic)
        {
            if (gameLogic.CurrentGame == null || gameLogic.CurrentGame.GameState != Game.GameStateEnum.Started)
            {
                throw new InvalidProgramException("CardFlipCommand.Execute() was called on an invalid game state");
            }

            // the StarTime can be null if this is the first card to be flipped - in that case store the offset as Zero
            if (gameLogic.CurrentGame.StartTime == null)
            {
                TimeOffset = TimeSpan.Zero;
            }
            else
            {
                DateTime startTime = (DateTime)gameLogic.CurrentGame.StartTime;
                TimeOffset = DateTime.Now - startTime;
            }

            gameLogic.CurrentGame.GameFlipCommands.Add(this);  // add this command to the list of commands run against this game
            return gameLogic.Flip(UniqueCardID);    // execute the flip command            
        }
    }
}
